<template>
  <div class="order-detail-container">
    <div class="page-header">
      <h2>订单详情</h2>
    </div>

    <el-card v-loading="isLoading">
      <!-- 订单状态 -->
      <div class="order-status-section">
        <div class="order-status-content">
          <el-icon class="status-icon"><i-ep-success /></el-icon>
          <div class="status-info">
            <h3>{{ getStatusText(order.status) }}</h3>
            <p v-if="order.status === 'pendingPayment'">请尽快完成支付，超时订单将自动取消</p>
            <p v-else-if="order.status === 'pendingShipment'">卖家正在备货中，请耐心等待</p>
            <p v-else-if="order.status === 'pendingReceipt'">商品已发出，请及时查收</p>
            <p v-else-if="order.status === 'completed'">感谢您的购买，欢迎再次光临</p>
            <p v-else-if="order.status === 'cancelled'">订单已取消</p>
          </div>
        </div>
        
        <div v-if="order.status === 'pendingPayment'" class="order-actions">
          <el-button type="primary" size="large" @click="payOrder">立即支付</el-button>
          <el-button size="large" @click="cancelOrder">取消订单</el-button>
        </div>
        
        <div v-else-if="order.status === 'pendingReceipt'" class="order-actions">
          <el-button type="primary" size="large" @click="confirmReceipt">确认收货</el-button>
          <el-button size="large" @click="checkLogistics">查看物流</el-button>
        </div>
      </div>

      <!-- 收货地址 -->
      <div class="section">
        <div class="section-title">收货信息</div>
        <div class="address-info">
          <div class="address-header">
            <span class="name">{{ order.address.name }}</span>
            <span class="phone">{{ order.address.phone }}</span>
          </div>
          <div class="address-detail">
            {{ order.address.province }} {{ order.address.city }} {{ order.address.district }} {{ order.address.detailAddress }}
          </div>
        </div>
      </div>

      <!-- 商品信息 -->
      <div class="section">
        <div class="section-title">商品信息</div>
        <div class="products-list">
          <div 
            class="product-item" 
            v-for="item in order.items" 
            :key="item.id"
            @click="goToProductDetail(item.id)"
          >
            <img :src="item.image" alt="商品图片" class="product-image">
            <div class="product-info">
              <div class="product-title">{{ item.title }}</div>
              <div class="product-price">¥{{ item.price.toFixed(2) }}</div>
              <div class="product-quantity">x{{ item.quantity }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 订单信息 -->
      <div class="section">
        <div class="section-title">订单信息</div>
        <div class="order-info">
          <div class="info-item">
            <span class="label">订单编号：</span>
            <span class="value">{{ order.id }}</span>
          </div>
          <div class="info-item">
            <span class="label">创建时间：</span>
            <span class="value">{{ formatDate(order.createdAt) }}</span>
          </div>
          <div class="info-item">
            <span class="label">支付方式：</span>
            <span class="value">{{ getPaymentMethodText(order.paymentMethod) }}</span>
          </div>
          <div v-if="order.paymentTime" class="info-item">
            <span class="label">支付时间：</span>
            <span class="value">{{ formatDate(order.paymentTime) }}</span>
          </div>
          <div v-if="order.remark" class="info-item">
            <span class="label">订单备注：</span>
            <span class="value">{{ order.remark }}</span>
          </div>
        </div>
      </div>

      <!-- 价格详情 -->
      <div class="section">
        <div class="section-title">价格详情</div>
        <div class="price-info">
          <div class="price-item">
            <span class="label">商品总价：</span>
            <span class="value">¥{{ order.subtotal.toFixed(2) }}</span>
          </div>
          <div class="price-item">
            <span class="label">运费：</span>
            <span class="value">¥{{ order.shippingFee.toFixed(2) }}</span>
          </div>
          <div class="price-item total">
            <span class="label">实付金额：</span>
            <span class="value total-price">¥{{ order.totalAmount.toFixed(2) }}</span>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useOrderStore } from '../../store'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
const orderStore = useOrderStore()
const isLoading = ref(true)

// 订单数据（模拟）
const order = ref({
  id: '',
  createdAt: '',
  paymentTime: '',
  status: '',
  paymentMethod: '',
  remark: '',
  items: [],
  address: {
    name: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    detailAddress: ''
  },
  subtotal: 0,
  shippingFee: 0,
  totalAmount: 0
})

onMounted(() => {
  const orderId = route.params.id
  if (orderId) {
    fetchOrderDetail(orderId)
  } else {
    ElMessage.error('未找到订单ID')
    router.push('/orders')
  }
})

const fetchOrderDetail = async (orderId) => {
  isLoading.value = true
  
  try {
    // 在实际项目中，这里应该从API获取订单详情
    // const orderData = await orderStore.fetchOrderDetail(orderId)
    // order.value = orderData
    
    // 模拟订单数据
    order.value = {
      id: orderId,
      createdAt: '2023-11-11 10:30:45',
      paymentTime: orderId === '202311090003' ? '2023-11-09 09:20:30' : '',
      status: orderId === '202311110001' ? 'pendingPayment' : 
              orderId === '202311100002' ? 'pendingShipment' :
              orderId === '202311090003' ? 'pendingReceipt' :
              orderId === '202311080004' ? 'completed' : 'cancelled',
      paymentMethod: 'wechat',
      remark: '尽快发货，谢谢',
      items: [
        {
          id: '101',
          title: '全新 小米13 8+256G 黑色 国行正品',
          image: '/images/phone1.jpg',
          price: 3599,
          quantity: 1
        },
        {
          id: '102',
          title: '小米原装充电器 67W 快充套装',
          image: '/images/charger1.jpg',
          price: 99,
          quantity: 1
        }
      ],
      address: {
        name: '张三',
        phone: '13800138000',
        province: '北京市',
        city: '北京市',
        district: '海淀区',
        detailAddress: '北京大学 1号公寓 301室'
      },
      subtotal: 3698,
      shippingFee: 0,
      totalAmount: 3698
    }
  } catch (error) {
    ElMessage.error('加载订单详情失败，请稍后重试')
    console.error('加载订单详情失败:', error)
    router.push('/orders')
  } finally {
    isLoading.value = false
  }
}

const formatDate = (dateString) => {
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss')
}

const getStatusText = (status) => {
  const statusMap = {
    pendingPayment: '待付款',
    pendingShipment: '待发货',
    pendingReceipt: '待收货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || '未知状态'
}

const getPaymentMethodText = (method) => {
  const methodMap = {
    wechat: '微信支付',
    alipay: '支付宝',
    cash: '货到付款'
  }
  return methodMap[method] || '未知支付方式'
}

const goToProductDetail = (productId) => {
  router.push(`/product/${productId}`)
}

const payOrder = () => {
  router.push(`/order/pay/${order.value.id}`)
}

const cancelOrder = async () => {
  try {
    await ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 在实际项目中，这里应该调用API取消订单
    order.value.status = 'cancelled'
    ElMessage.success('订单已取消')
  } catch (error) {
    // 用户取消操作，不做任何处理
  }
}

const confirmReceipt = async () => {
  try {
    await ElMessageBox.confirm('确认已收到商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 在实际项目中，这里应该调用API确认收货
    order.value.status = 'completed'
    ElMessage.success('已确认收货')
  } catch (error) {
    // 用户取消操作，不做任何处理
  }
}

const checkLogistics = () => {
  ElMessage.info('正在查询物流信息...')
  // 实际项目中应该显示物流详情
}
</script>

<style scoped>
.order-detail-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h2 {
  font-size: 24px;
  color: #333;
}

.section {
  margin-top: 30px;
  padding-top: 30px;
  border-top: 1px solid #e0e0e0;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
}

/* 订单状态区域 */
.order-status-section {
  background: #f0f9eb;
  padding: 30px;
  border-radius: 8px;
  text-align: center;
}

.status-icon {
  font-size: 60px;
  color: #67c23a;
  margin-bottom: 20px;
}

.status-info h3 {
  font-size: 24px;
  color: #333;
  margin-bottom: 10px;
}

.status-info p {
  color: #666;
  margin-bottom: 20px;
}

.order-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
}

/* 地址信息 */
.address-info {
  padding: 20px;
  background: #fafafa;
  border-radius: 4px;
}

.address-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 10px;
}

.name {
  font-weight: bold;
  color: #333;
}

.phone {
  color: #666;
}

.address-detail {
  color: #666;
  line-height: 1.5;
}

/* 商品列表 */
.products-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.product-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.product-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 20px;
}

.product-info {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.product-title {
  flex: 1;
  font-size: 16px;
  color: #333;
  margin-right: 20px;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-price {
  color: #ff4d4f;
  font-weight: bold;
  margin-right: 20px;
}

.product-quantity {
  color: #999;
}

/* 订单信息和价格详情 */
.order-info,
.price-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.info-item,
.price-item {
  display: flex;
  justify-content: space-between;
  color: #666;
}

.label {
  font-weight: 500;
}

.price-item.total {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e0e0e0;
  font-size: 18px;
}

.total-price {
  font-size: 24px;
  font-weight: bold;
  color: #ff4d4f;
}

@media (max-width: 768px) {
  .order-status-section {
    padding: 20px;
  }
  
  .status-icon {
    font-size: 40px;
  }
  
  .status-info h3 {
    font-size: 20px;
  }
  
  .order-actions {
    flex-direction: column;
    gap: 10px;
  }
  
  .address-header {
    flex-wrap: wrap;
  }
  
  .product-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .product-image {
    margin-right: 0;
  }
  
  .product-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .product-title {
    margin-right: 0;
  }
  
  .info-item,
  .price-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
  
  .total-price {
    font-size: 20px;
  }
}
</style>